<?php

namespace App\Http\Controllers\home;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class DetailController extends Controller
{

     //进行遍历类别
    static public function getCate($pid){
        //定义一个空数组
        $cate=array();
        //通过传过来的pid查询类别表
        $data=DB::table('cate')->where('pid','=',$pid)->get();
        //遍历查询到的数据
        foreach($data as $k=>$v){
            //通过自身的id去掉用自身的方法(通过pid查询) 判断下面是否还存在子分类 如果有就把他压入自身的一个下标中
            $v['fenlei']=self::getCate($v['cid']);
            //将每次得到的数据遍历到空数组中
            $cate[]=$v;
        }
         return $cate;
    } 

    //显示商品详情页
    public function getIndex(Request $request){
        
        //把得到的数据发送到模板进行遍历
        $cate=self::getCate(0);

        $gid=$request->input('gid');
        $data=DB::table('goods')->where('gid',$gid)->get();
        DB::table('goods')->where('gid',$gid)->increment("hot",1);
        $hot=DB::table('goods')->orderBy('hot','')->limit(5)->get();


        // 判断是否收藏了该商品        
        $coll = DB::table('collect') -> where('h_uid',session('h_user')['h_uid']) -> where('gid',$gid) -> count();

        // 评论
        $comment = DB::table('comment') -> join('home_user','comment.uid','=','home_user.h_uid') -> where('gid',$gid) -> orderBy('time', 'desc') -> paginate(10);

        // 好中差评计算
        $comment2 = DB::table('comment') -> where('gid',$gid) -> get();
        $pingjia = ['hao'=>0,'zhong'=>0,'cha'=>0,'zong'=>0];
        foreach($comment2 as $k => $v){
            if($v['eval']==1){
                // 好评数+1 总评数+1
                $pingjia['hao'] += 1;
                $pingjia['zong'] += 1;
            }elseif($v['eval']==2){
                $pingjia['zhong'] += 1;
                $pingjia['zong'] += 1;
            }elseif($v['eval']==3){
                $pingjia['cha'] += 1;
                $pingjia['zong'] += 1;
            }
        }
        if($pingjia['zong']==0){
            $pingjia['zong']=1;
        }
        $pingjiawen = ['1' => '好评','2' => '中评','3' => '差评'];

        return view('/home/detail/index',['cate'=>$cate,'hot'=>$hot,'data'=>$data[0],'coll' => $coll,'comment' => $comment,'pingjia'=>$pingjia,'pingjiawen'=>$pingjiawen]);
    }
}
